angular.module('app')

.controller('StockListController', function($scope,$timeout,StockService,StockCategoryService,IndexService) {
	
	// paginations
	$scope.paginationConf = {
            currentPage: 1,
            totalItems: 0,
            itemsPerPage: 10,
            pagesLength: 7,
            perPageOptions: [10,25,50],
            rememberPerPage: 'perPageItems',
            onChange: function(){
				StockService.getAllStocksByType($scope.tabindex, $scope.paginationConf.currentPage, $scope.paginationConf.itemsPerPage).success( 
					function(data) {
						$scope.stocks = data;
						$scope.selectedStock = data[0];
						$scope.selectedIndex = 0;
						$scope.selectCurrentStock($scope.selectedIndex);
					}
				);
            }
        };
	$scope.pagiConf4Index = {
            currentPage: 1,
            totalItems: 0,
            itemsPerPage: 10,
            pagesLength: 7,
            perPageOptions: [10,25,50],
            rememberPerPage: 'perPageItems',
            onChange: function(){
				IndexService.findAllIndexes($scope.pagiConf4Index.currentPage, $scope.pagiConf4Index.itemsPerPage).success( 
					function(data) {
						$scope.indexes = data;
						$scope.selectedRow = data[0];
						$scope.selectedIndex = 0;
						$scope.selectCurrentIndex($scope.selectedIndex);
					}
				);
            }
        };
	$scope.pagiConf4SelfSelects = {
            currentPage: 1,
            totalItems: 100,
            itemsPerPage: 10,
            pagesLength: 7,
            perPageOptions: [10,25,50],
            rememberPerPage: 'perPageItems',
            onChange: function(){
            	StockService.findAllSelfSelects($scope.pagiConf4SelfSelects.currentPage, $scope.pagiConf4SelfSelects.itemsPerPage).success( 
					function(data) {
						$scope.selfSelects = data;
						$scope.selectedSelfSelect = data[0];
						$scope.selectedIndex = 0;
						$scope.selectCurrentSelfSelect($scope.selectedIndex);
					}
				);
            }
        };
		
	// init pages
	$scope.initStockPage = function() {
		StockService.getStockNumByType($scope.tabindex).success(
			function(data) {
				$scope.paginationConf.totalItems = data;
				StockService.getAllStocksByType($scope.tabindex, $scope.paginationConf.currentPage, $scope.paginationConf.itemsPerPage).success( 
					function(data) {
						$scope.stocks = data;
						$scope.selectedStock = data[0];
						$scope.selectedIndex = 0;
						$scope.selectCurrentStock($scope.selectedIndex);
					}
				);
			}
		);
	};
	
	$scope.initIndexPage = function() {
		IndexService.getIndexNum().success(
			function(data) {
				$scope.pagiConf4Index.totalItems = data;
				IndexService.findAllIndexes($scope.pagiConf4Index.currentPage, $scope.pagiConf4Index.itemsPerPage).success( 
					function(data) {
						$scope.indexes = data;
						$scope.selectedRow = data[0];
						$scope.selectedIndex = 0;
						$scope.selectCurrentIndex($scope.selectedIndex);
					}
				);
			}
		);
	};
	
	$scope.initSelfSelectsPage = function() {
		StockService.getSelfSelectNum().success(
			function(data) {
				$scope.pagiConf4SelfSelects.totalItems = data;
				StockService.findAllSelfSelects($scope.pagiConf4SelfSelects.currentPage, $scope.pagiConf4SelfSelects.itemsPerPage).success( 
					function(data) {
						$scope.selfSelects = data ? data : [];
						console.log("get " + $scope.selfSelects.length + " selfSelects");
						if (!$scope.selfSelects.length==0) {
							$scope.selectedSelfSelect = data[0];
							$scope.selectedIndex = 0;
							$scope.selectCurrentSelfSelect($scope.selectedIndex);
						}
					}
				);
			}
		);
	};
	
	$scope.initPageByTabIndex = function() {
		var tabindex = $scope.tabindex;
		if (tabindex == 1 || tabindex == 2) {
			$scope.currentTab = "stock";
			$scope.initStockPage();
		} else if (tabindex == 3) {
			$scope.currentTab = "index";
			$scope.initIndexPage();
		} else if (tabindex == 4) {
			$scope.currentTab = "selfselect";
			$scope.initSelfSelectsPage();
		}
	};
	
	// creation
    $scope.createStock=function() {
        $scope.stocks.splice(0,0,{code:'', name:'', status:''});
		$scope.paginationConf.totalItems = $scope.paginationConf.totalItems + 1;
    };
	
	$scope.createSelfSelect=function() {
        $scope.selfSelects.splice(0,0,{code:'', name:'', status:''});
		$scope.pagiConf4SelfSelects.totalItems = $scope.pagiConf4SelfSelects.totalItems + 1;
    };
    
	$scope.createStockCategory=function() {
		if ($scope.currentTab=="stock") {
			$scope.categoriesByStock.splice($scope.categoriesByStock.length, 0, {name:''});
		} else if ($scope.currentTab=="selfselect") {
			$scope.categoriesBySelfSelect.splice($scope.categoriesBySelfSelect.length, 0, {name:''});
		}
		console.log("end calling createStockCategory");
	};
	

	// events
	$scope.changeTab=function(target) {
		// get li element
		var jqueryObj = angular.element(target).parent();
		
		$('.nav-tabs li').removeClass("active");
		jqueryObj.addClass("active");
		
		$scope.tabindex = $('.nav-tabs .active').index()+1;
		$scope.initPageByTabIndex();
		
    };
	
	//////// selection events
	$scope.tagClasses = ['estag label label-default','estag label label-primary',
					'estag label label-success','estag label label-info',
					'estag label label-warning','estag label label-danger'];
	$scope.selectCurrentStock=function(index) {
		// used for showing name and code
    	$scope.selectedStock = $scope.stocks[index];
    	$scope.selectedIndex = index;
		StockCategoryService.findCategoriesByStockId($scope.selectedStock.id).success( 
			function(data) {
				$scope.categoriesByStock = data;
				// shuffle tagClasses in order to get random color.
				$scope.tagClasses.sort(function(a, b){
					return (0.5 - Math.random());
				});
				
				$timeout(function() {
					$('#categoryTagMsg').html(
							'<div class="alert alert-info alert-dismissable" style="height:26px;padding-top:3px;margin:5px 0px;">' +
							'<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>' +
							'<i class="icon fa fa-info"></i> You can add/remove stock categories here!</div>');
		        }, 5000);
			}
		);
    };
	// this index is not that index...
	$scope.selectCurrentIndex=function(index) {
		// used for showing name and code
    	$scope.selectedRow = $scope.indexes[index];
    	$scope.selectedIndex = index;
    };
	$scope.selectCurrentSelfSelect=function(index) {
		// used for showing name and code
    	$scope.selectedSelfSelect = $scope.selfSelects[index];
    	$scope.selectedIndex = index;
    	if ($scope.selectedSelfSelect.code) {
    		StockCategoryService.findCategoriesByStockCode($scope.selectedSelfSelect.code).success( 
				function(data) {
					$scope.categoriesBySelfSelect = data;
					// shuffle tagClasses in order to get random color.
					$scope.tagClasses.sort(function(a, b){
						return (0.5 - Math.random());
					});
					
					$timeout(function() {
						$('#categoryTagMsg').html(
								'<div class="alert alert-info alert-dismissable" style="height:26px;padding-top:3px;margin:5px 0px;">' +
								'<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>' +
								'<i class="icon fa fa-info"></i> You can add/remove stock categories here!</div>');
			        }, 5000);
					
				}
			);
    	}

    };
	
	
	$scope.deleteStockById=function(stockId) {
		return; // disable deleting stock
		StockService.deleteStockById(stockId).success( 
			function(data) {
				for(var i=0; i<$scope.stocks.length; i++){
					if($scope.stocks[i].id==stockId){
						$scope.stocks.splice(i,1);
						if ($scope.stocks.length > 0) {
							$scope.selectCurrentStock(0);
						} else {
							$scope.selectedStock = undefined;
							$scope.categoriesByStock = undefined;
						}
					}
				}	
			}
		).error(
			function(data, status, headers, config) {
				$('#warningMsgForStock').html("<font color='red'>Error in deleting selected stock!</font>");
				return;
			}
		);
    };
	
	$scope.deleteSelfSelectById=function(stockId) {
		StockService.deleteSelfSelectById(stockId).success( 
			function(data) {
				for(var i=0; i<$scope.selfSelects.length; i++){
					if($scope.selfSelects[i].id==stockId){
						$scope.selfSelects.splice(i,1);
						if ($scope.selfSelects.length > 0) {
							$scope.selectCurrentSelfSelect(0);
						} else {
							$scope.selectedSelfSelect = undefined;
							$scope.categoriesBySelfSelect = [];
						}
					}
				}	
			}
		).error(
			function(data, status, headers, config) {
				$('#warningMsgForStock').html("<font color='red'>Error in deleting selected stock!</font>");
				return;
			}
		);
    };
	
	$scope.saveStockCategory=function() {
		console.log("start calling saveStockCategory");
		
		if ($scope.currentTab=="stock") {
			var code = $scope.selectedStock.code;
			var newCategory = $scope.categoriesByStock[$scope.categoriesByStock.length-1];
		} else if ($scope.currentTab=="selfselect") {
			var code = $scope.selectedSelfSelect.code;
			var newCategory = $scope.categoriesBySelfSelect[$scope.categoriesBySelfSelect.length-1];
		}
		
		// encounter odd issue while trying to use post
		StockCategoryService.saveStockCategoryWithCode(code, newCategory.name).success( 
			function(data) {
				if ($scope.currentTab=="stock") {
		    		for(var i=0; i<$scope.categoriesByStock.length; i++){
	                    if($scope.categoriesByStock[i].name==data.name){
	                        $scope.categoriesByStock[i] = data;
	                    }
	                }
				} else if ($scope.currentTab=="selfselect") {
		    		for(var i=0; i<$scope.categoriesBySelfSelect.length; i++){
	                    if($scope.categoriesBySelfSelect[i].name==data.name){
	                        $scope.categoriesBySelfSelect[i] = data;
	                    }
	                }
				}
	    	}
		);
	};
	
	$scope.refreshSelfSelectPrices = function() {
		$timeout(function() {
			if ($scope.tabindex == 4) {
				if (isTransTime()) {
//					console.log("start getting currentPrices for all selfSelects");
					StockService.getCurrentPrices($scope.selfSelects).success(
						function(data) {
							for(var i=0; i<$scope.selfSelects.length; i++){
								$scope.selfSelects[i].latestPrice = data[i];
							} 
						}
					);
				} else {
//					console.log("freshing currentPrices with yester price");
					for(var i=0; i<$scope.selfSelects.length; i++){
						$scope.selfSelects[i].latestPrice = $scope.selfSelects[i].latestPrice;
					} 
				}
			} 
            $scope.refreshSelfSelectPrices();
        }, 5000);
	}
	
	////////////////// Initialization /////////////////////
	$scope.currentPage = "StockMgr";
	
    // used for e/u/d stock
    $scope.showStockEdit = true;
    $scope.master = {};
	
	$scope.stocks = [];
	$scope.selfSelects = [];
	$scope.tabindex = 4;
	
	$scope.initPageByTabIndex();
	$scope.refreshSelfSelectPrices();
    ////////////////// Initialization /////////////////////

})